iT邦幫忙

2026 iThome 鐵人賽

DAY 2
1
Software Development

快樂演算法系列 第 2

Auto training & gpt 今天好怪 &417初版 明日再繼續

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20260821/20177944FoFMtPQg2I.jpg

https://ithelp.ithome.com.tw/upload/images/20260821/20177944BYooZaF9gN.png

class Solution {//m*n
public:
    vector<vector<int>> pacificAtlantic(vector<vector<int>>& height) {
        int rows = height.size();
        int cols = height[0].size();
        vector<vector<char>> pacific(rows, vector<char>(cols, 0));
        vector<vector<char>> atlantic(rows, vector<char>(cols, 0));

        int directions[4][2] = {
            {1, 0}, {-1, 0}, {0, 1}, {0, -1}
        };

        auto dfs = [&](auto&& dfs, int row, int col,
                       vector<vector<char>>& visited) -> void {

            visited[row][col] = 1;

            for (auto& direction : directions) {
                int nextRow = row + direction[0];
                int nextCol = col + direction[1];

                if (nextRow < 0 || nextRow >= rows ||
                    nextCol < 0 || nextCol >= cols)
                    continue;

                if (visited[nextRow][nextCol])
                    continue;

                if (height[nextRow][nextCol] < height[row][col])
                    continue;

                dfs(dfs, nextRow, nextCol, visited);
            }
        };

        for (int col = 0; col < cols; ++col) {
            dfs(dfs, 0, col, pacific);              // 上
            dfs(dfs, rows - 1, col, atlantic);      // 下
        }

        for (int row = 0; row < rows; ++row) {
            dfs(dfs, row, 0, pacific);              // 左
            dfs(dfs, row, cols - 1, atlantic);      // 右
        }

        vector<vector<int>> answer;

        for (int row = 0; row < rows; ++row)
            for (int col = 0; col < cols; ++col)
                if (pacific[row][col] && atlantic[row][col])
                    answer.push_back({row, col});

        return answer;
    }
};

上一篇
LSTM :'( YOLOE:)& 過度緩慢記憶+連滾帶爬發文 841
系列文
快樂演算法2
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言